package com.nd.android.u.ui.widge;

import ims.utils.CommUtil;
import ims.utils.SdCardUtils;

import java.io.IOException;
import java.util.ArrayList;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.common.android.utils.smiley.Smiley;
import com.common.android.utils.smiley.Smileyhelper;
import com.nd.android.u.allCommonUtils.FileHelper;
import com.nd.android.u.allCommonUtils.LogUtils;
import com.nd.android.u.allCommonUtils.ToastUtils;
import com.nd.android.u.controller.ChatConst;
import com.nd.android.u.controller.ChatConst.MessageContentType;
import com.nd.android.u.controller.bean.ImageMessage;
import com.nd.android.u.controller.factory.ShareFileFactory;
import com.nd.android.u.controller.innerInterface.IChatListItem;
import com.nd.android.u.controller.innerInterface.IMessageDisplay;
import com.nd.android.u.controller.innerInterface.IShareFile;
import com.nd.android.u.ui.ChatEntry;
import com.nd.android.u.ui.R;
import com.nd.android.u.ui.activity.chat_relative_image.ShowImagesActivity;
import com.nd.android.u.ui.chatUiUtils.ChatViewUtil;
import com.nd.android.u.ui.chatUiUtils.LocalImageManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.product.android.business.ApplicationVariable;
import com.product.android.business.Const;

/**
 * 聊天界面图片控件：具体实现在父类 <br>
 * Created 2014-5-6 下午5:16:54
 * 
 * @version
 * @author cb
 * 
 * @see
 */
public class ChatListItemView_Image extends RelativeLayout implements IChatListItem{
    public static final int PIC_GIF = 0;
    public static final int PIC_NORMAL = 1;
    public static final int HIGHER_METRICS = 440;
    public static final int LOWER_METRICS = 120;
//    private static final int MAX_DOWNLOAD_GIF_FILE_SIZE = 10 * 1024; // 允许在非WIFI环境下下载的GIF图片的最大文件尺寸
//    private static final int MAX_DOWNLOAD_GIF_FILE_SIZE_WIFI = 800 * 1024; // 允许在WIFI环境下下载的GIF图片的最大文件尺寸
//    private static final int MAX_DOWNLOAD_GIF_MEASURE_SIZE = 50; // 允许在非WIFI环境下下载的GIF图片的最大图形尺寸
    protected Context mContext;
    protected IMessageDisplay mMessage;
    /** 用于显示动画的控件 */
    protected GifImageView imgGif;
    /** 用于显示普通图片的控件 */
    protected ImageView imgNormal;
    /** gif标志，用于提示用户该图片是gif（实际上并不一定是） */
    protected ImageView imgGifIcon;
	/**
	 * ChatListItemView_Image.构造方法
	 * <br>Created 2014-9-12 上午11:30:21
	 * @param context
	 */
	public ChatListItemView_Image(Context context) {
		super(context);
		initView(context);
	}

	/**
	 * ChatListItemView_Image.构造方法
	 * <br>Created 2014-9-12 上午11:30:23
	 * @param context
	 * @param attrs
	 */
	public ChatListItemView_Image(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}
    
	/**
	 * 初始化控件
	 * <br>Created 2014-10-30 下午2:25:18
	 * @param context
	 * @author  cb
	*/
	private void initView(Context context) {
		mContext = context;
		LayoutInflater.from(context).inflate(R.layout.chat_list_item_image, this, true);
		imgGif = (GifImageView) findViewById(R.id.gifpic);
		imgNormal = (ImageView) findViewById(R.id.norpic);
		imgGifIcon = (ImageView) findViewById(R.id.defaultgif);
	}
	
	// clickBubble:点击气泡体
    private OnClickListener clickBubble = new OnClickListener() {
        @Override
        public void onClick(View v) {
            String path = mMessage.getPath();
            if (mMessage.isFromSelf() && !TextUtils.isEmpty(path)) {
                viewLocalImg(path, mMessage.getThumbnailPath());
            } else {
                ArrayList<Object> datas = mMessage.getDisplayDatas();
                ArrayList<String> imgUrlList = new ArrayList<String>();
                ArrayList<String> thumbUrlList = new ArrayList<String>();
                for (Object obj : datas) {
                    if (obj instanceof ImageMessage) {
                        ImageMessage imageMessage = (ImageMessage) obj;
                        int type=MessageContentType.PICTURE;
						IShareFile shareFile=ShareFileFactory.INSTANCE.getShareFileInterface(IShareFile.DOWNLOAD, type);
				        String url=shareFile.getShareFileUrl(imageMessage.getImgurl(), "", type);
                        imgUrlList.add(url);
                        if (ApplicationVariable.INSTANCE.displayMetrics.heightPixels > 1000
                                || ApplicationVariable.INSTANCE.displayMetrics.widthPixels > 1000) {
                            url += "&thumb=440";
                        } else {
                            url += "&thumb=120";
                        }
                        thumbUrlList.add(url);
                    }
                }
                viewImg(imgUrlList, thumbUrlList);
            }
        }
    };

    /**
     * 查看本地图片 <br>
     * Created 2014-7-22 下午6:07:53
     * 
     * @author cb
     */
    private void viewLocalImg(String path, String thumbPath) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        ArrayList<String> imgUrlList = new ArrayList<String>();
        imgUrlList.add(FileHelper.getFileUri(path));
        if (!TextUtils.isEmpty(thumbPath)) {
            // 如果有缩略图,把相应的路径送过去.
            ArrayList<String> thumbUrlList = new ArrayList<String>();
            thumbUrlList.add(FileHelper.getFileUri(thumbPath));
            bundle.putStringArrayList(Const.BUNDLE_KEY.THUMB_LIST, thumbUrlList);
        }
        bundle.putStringArrayList(Const.BUNDLE_KEY.URL_LIST, imgUrlList);
        bundle.putBoolean("chat", true);
        intent.putExtras(bundle);
        intent.setClass(getContext(), ShowImagesActivity.class);
        getContext().startActivity(intent);
    }

    /**
     * 查看网络图片 <br>
     * Created 2014-7-22 下午6:15:12
     * 
     * @param imgUrlList
     * @param thumbUrlList
     * @author cb
     */
    private void viewImg(ArrayList<String> imgUrlList, ArrayList<String> thumbUrlList) {
        if (!SdCardUtils.isSdCardExist()) {
            ToastUtils.display(R.string.sdcard_not_found);
            return;
        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putStringArrayList(Const.BUNDLE_KEY.URL_LIST, imgUrlList);
        bundle.putStringArrayList(Const.BUNDLE_KEY.THUMB_LIST, thumbUrlList);
        bundle.putBoolean("chat", true);
        intent.putExtras(bundle);
        intent.setClass(getContext(), ShowImagesActivity.class);
        getContext().startActivity(intent);
    }

    /**
     * 回收图片 <br>
     * Created 2014-5-6 下午5:30:27
     * 
     * @author cb
     */
    public void recycle() {
        imgNormal.setImageBitmap(null);
    }

    @Override
    public void setData(IMessageDisplay message) {
        mMessage = message;
        if (!SdCardUtils.isSdCardExist()) {
            // 没有SD卡
            setBackgroundResource(R.drawable.failed);
            return;
        }
        imgGif.setVisibility(View.GONE);
        imgNormal.setVisibility(View.GONE);
        imgGifIcon.setVisibility(View.GONE);
        if (message.isFromSelf() && !TextUtils.isEmpty(message.getPath())) {
            // 是本地发送的图片(本地发的图片的filename字段不为空)
            setUploadImage(message);
        } else {
            setDownloadImage(message);
        }
    }

    /**
     * 显示从本地发送的图片 <br>
     * Created 2014-8-2 下午4:34:10
     * 
     * @author cb
     */
    private void setUploadImage(IMessageDisplay message) {
        GifDrawable gifDrawable = getGif(message.getPath());
        if (gifDrawable != null) {
            changeVisible(true);
            setGifSize(imgGif,mMessage.getPath());
            imgGif.setBackgroundDrawable(gifDrawable);
        } else {
            changeVisible(false);
            String path = mMessage.getThumbnailPath();
            if (TextUtils.isEmpty(path)) {
                // 没有缩略图,是旧版的,直接显示原图
                path = mMessage.getPath();
            }
            Bitmap bmp = LocalImageManager.INSTANCE.get(mContext, path);
            ChatViewUtil.resetImageViewParams(imgNormal, path);
            imgNormal.setImageBitmap(bmp);
        }
    }

    /**
     * 显示下载的图片 <br>
     * Created 2014-8-2 下午4:34:47
     * 
     * @author cb
     */
    private void setDownloadImage(IMessageDisplay message) {
        if (setCatGif(message)) {
            return;
        }
        if (setAlreadyDownloadImage(message)) {
            LogUtils.d(LogUtils.CHAT, "setAlreadyDownloadImage:" + message.getUrl());
            return;
        }
        String url = message.getUrl();
        // 先从文件名上判断是否是一个gif图
        if (CommUtil.isGifPicture(url)) {
            // 文件名上看是一个gif，设置gif图片，显示原图
            LogUtils.d(LogUtils.CHAT, "set gif :url=" + url);
            setNormalGif(message);
        } else {
            LogUtils.d(LogUtils.CHAT, "set normal :url=" + url);
            imgNormal.setVisibility(View.VISIBLE);
            // 非gif（虽然实际上有可能是）,显示缩略图
            String thumbUrl = message.getThumbnailUrl();
            Log.e("lizard", "thumbUrl"+thumbUrl);
            if (TextUtils.isEmpty(thumbUrl)) {
                // 取不到url（thumburl为空说明url也为空,显示失败的图片。不过其实url为空在setAlreadyDownloadImage方法里已判断过了，这里再判断一次只是为了保险起见
                LogUtils.e(LogUtils.CHAT, "setDownloadImage fail:null url");
                imgNormal.setBackgroundResource(R.drawable.failed);
                return;
            }
            String path = ImageLoader.getInstance().getDiscCacheFileAbsPath(
                    ChatEntry.INSTANCE.chatOptions, thumbUrl);
            if (!TextUtils.isEmpty(path)) {
                // 图片已下载，根据图片重置控件的大小
                ChatViewUtil.resetImageViewParams(imgNormal, path);
            }
            GifDrawable drawable=getGif(path);
            if (drawable==null){
                imgNormal.setVisibility(View.VISIBLE);
                imgGif.setVisibility(View.GONE);
            	ImageLoader.getInstance().displayImage(thumbUrl, imgNormal,
                        ChatEntry.INSTANCE.chatOptions, loadingListener);	
            }else{
            	imgGif.setVisibility(View.VISIBLE);
                imgGif.setBackgroundDrawable(drawable);
                imgGifIcon.setVisibility(View.GONE);
                imgNormal.setVisibility(View.GONE);
                ChatViewUtil.resetImageViewParams(imgGif, path);
//                setGifSize(imgGif, path);
            }
        }
    }

    /**
     * 
     * <br>
     * Created 2014-8-4 上午10:32:51
     * 
     * @return true表示图片已加载完毕，不需要再往下处理
     * @author cb
     */
    private boolean setAlreadyDownloadImage(IMessageDisplay message) {
        String url = message.getUrl();
        if (TextUtils.isEmpty(url)) {
            // 没有url
            LogUtils.e(LogUtils.CHAT, "setDownloadImage fail:null url");
            imgNormal.setBackgroundResource(R.drawable.failed);
            return true;
        }
        // 根据url获取本地的路径
        String path = ImageLoader.getInstance().getDiscCacheFileAbsPath(
                ChatEntry.INSTANCE.chatOptions, url);
        if (TextUtils.isEmpty(path)) {
            // 图片未下载完成，继续下面的处理
            return false;
        }
        GifDrawable drawable = getGif(path);
        if (drawable == null) {
            // 下载下来的图片实际上并不是一个gif
            imgNormal.setImageBitmap(LocalImageManager.INSTANCE.get(mContext, path));
            imgNormal.setVisibility(View.VISIBLE);
            imgGif.setVisibility(View.GONE);
            ChatViewUtil.resetImageViewParams(imgNormal, path);
        } else {
            imgGif.setVisibility(View.VISIBLE);
            imgNormal.setVisibility(View.GONE);
            imgGif.setBackgroundDrawable(drawable);
            imgGifIcon.setVisibility(View.GONE);
            setGifSize(imgGif, path);
            //ChatViewUtil.resetImageViewParams(imgGif, path);
        }
        return true;
    }

    /**
     * 显示普通的gif图片 <br>
     * Created 2014-8-4 上午10:10:32
     * 
     * @param message
     *            消息
     * @author cb
     */
    private void setNormalGif(IMessageDisplay message) {
        String url = message.getUrl();
        // 未获取到本地路径，即未下载成功
        imgGifIcon.setVisibility(View.VISIBLE);
        imgNormal.setVisibility(View.VISIBLE);
        imgNormal.setImageBitmap(LocalImageManager.INSTANCE.getStartBitmap());
        ImageLoader.getInstance().displayImage(url, imgNormal, ChatEntry.INSTANCE.chatOptions,
                loadingListener);
    }

    /**
     * 显示猫表情动画 <br>
     * Created 2014-8-2 下午5:06:51
     * 
     * @return true 表示是一个猫表情，不用继续处理
     * @author cb
     */
    private boolean setCatGif(IMessageDisplay message) {
        ArrayList<Object> datas = message.getDisplayDatas();
        if (!datas.isEmpty()) {
            Object obj = datas.get(0);
            if (obj instanceof ImageMessage) {
                ImageMessage imageMessage = (ImageMessage) obj;
                if (imageMessage.getType() == ImageMessage.SMILY_TYPE) {
                    int id = Integer.parseInt(imageMessage.getImgurl());
                    Smiley smiley = Smileyhelper.getInstance().getSmiley(id);
                    try {
                        changeVisible(true);
                        GifDrawable gifDrawable = new GifDrawable(mContext.getAssets(),
                                smiley.gifName);
                        imgGif.setBackgroundDrawable(gifDrawable);
                        ViewGroup.LayoutParams lp = imgGif.getLayoutParams();
                        if (lp == null) {
                            lp = new ViewGroup.LayoutParams(-1, -1);
                        }
                        lp.height = gifDrawable.getIntrinsicHeight();
                        lp.width = gifDrawable.getIntrinsicWidth();
                        imgGif.setLayoutParams(lp);
                        return true;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return false;
    }

    private ImageLoadingListener loadingListener = new ImageLoadingListener() {
        @Override
        public void onLoadingStarted(String arg0, View arg1) {
        }

        @Override
        public void onLoadingProgress(long arg0, long arg1) {
        }

        @Override
        public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
            LogUtils.e(LogUtils.CHAT, "onLoadingFailed:" + arg0);
        }

        @Override
        public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
            String path = ImageLoader.getInstance().getDiscCacheFileAbsPath(
                    ChatEntry.INSTANCE.chatOptions, arg0);
            if (!TextUtils.isEmpty(path)) {
                GifDrawable gifDrawable = getGif(path);
                if (gifDrawable != null) {
                    Message message = gifHandler.obtainMessage(PIC_GIF);
                    Bundle pathBundle=new Bundle();
                    pathBundle.putString("path", path);
                    message.setData(pathBundle);
                    message.obj = gifDrawable;
                    gifHandler.sendMessage(message);
                    return;
                } else {
                    Message message = gifHandler.obtainMessage(PIC_NORMAL);
                    message.obj = arg0;
                    gifHandler.sendMessage(message);
                }
            } else {
                LogUtils.e(LogUtils.CHAT, "onLoadingComplete and path is null:" + arg0);
            }

        }

        @Override
        public void onLoadingCancelled(String arg0, View arg1) {
            LogUtils.e(LogUtils.CHAT, "onLoadingCancelled:" + arg0);
        }
    };

    /**
     * 用gif控件显示或者用Imageview显示
     */
    Handler gifHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == PIC_NORMAL) {
                changeVisible(false);
            } else {
                Bundle pathbuBundle=msg.getData();
                changeVisible(true);
                setGifSize(imgGif, pathbuBundle.getString("path"));
                imgGif.setBackgroundDrawable((Drawable) msg.obj);
            }

        };
    };

    /**
     * 是否显示gif控件 <br>
     * Created 2014-7-29 下午3:00:03
     * 
     * @param isGif
     *            isGif
     * @author mengnan
     */
    public void changeVisible(boolean isGif) {
        if (isGif) {
            imgNormal.setVisibility(View.GONE);
            imgGif.setVisibility(View.VISIBLE);
            imgGifIcon.setVisibility(View.GONE);

        } else {
        	
        	//addstart by rfb logtime20141107 forBUF 54695 
        	String path = ImageLoader.getInstance().getDiscCacheFileAbsPath(
                    ChatEntry.INSTANCE.chatOptions, mMessage.getThumbnailUrl());
        	
            if (!TextUtils.isEmpty(path)) {
                // 图片已下载，根据图片重置控件的大小
                ChatViewUtil.resetImageViewParams(imgNormal, path);
            } 
            //add end
        	
            imgNormal.setVisibility(View.VISIBLE);
            imgGif.setVisibility(View.GONE);
        }
    }

    @Override
    public IMessageDisplay getData() {
        return mMessage;
    }

//    private void checkDownloadOriBitmap(final String url) {
//        new Thread(new Runnable() {
//            public void run() {
//                // 获取文件大小
//                long size = mMessage.getFileSize();
//                if (size == 0) {
//                    // android.util.LogUtils.d("image_error", "get file len:"+size+",url="+url);
//                    size = CommonUtils.getFileSize(url);
//                    // 把文件的大小保存下来，不要每次都去取
//                    // mImageMessage.setLength(size);
//                }
//                if (IMSStateManager.getInstance().isWifi()) {
//                    // WIFI环境
//                    if (size <= MAX_DOWNLOAD_GIF_FILE_SIZE_WIFI) {
//                        Message message = handler.obtainMessage();
//                        message.obj = url;
//                        handler.sendMessage(message);
//                    }
//                } else {
//                    if (IMSStateManager.getInstance().isNetworkAvailable()) {
//                        if (size == 0) {
//                            // 非WIFI环境下取到的文件的尺寸为0，可能出现错误，不下载文件
//                        }
//                        if (size <= MAX_DOWNLOAD_GIF_FILE_SIZE) {
//                            // 图片的文件大小未超过限制，直接下载
//                            Message message = handler.obtainMessage();
//                            message.obj = url;
//                            handler.sendMessage(message);
//                        }
//                    }
//                }
//            }
//        }).start();
//    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // setDownloadImageLayout(mNormalImage, mMessage.getUrl());
        };
    };

    /**
     * 根据路径获取gif图片 <br>
     * Created 2014-8-2 下午4:56:23
     * 
     * @param path
     *            路径
     * @return gif图片
     * @author cb
     */
    private GifDrawable getGif(String path) {
        try {
            return new GifDrawable(path);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 设置gif的缩略图 <br>
     * Created 2014-8-4 下午4:52:21
     * 
     * @param img
     *            GifImageView
     * @author mengnan
     */
    public void setGifSize(GifImageView img, String path) {
        Log.e("lizard", "setGifSize"+mMessage.getUrl());
        ViewGroup.LayoutParams lp = img.getLayoutParams();
        Options options = new Options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(path, options);
        if (lp == null) {
            lp = new ViewGroup.LayoutParams(-1, -1);
        }
        lp.width=options.outWidth;
        lp.height=options.outHeight;
        if (ApplicationVariable.INSTANCE.displayMetrics.heightPixels >= ChatConst.BIG_SCREEN
                || ApplicationVariable.INSTANCE.displayMetrics.widthPixels >= ChatConst.BIG_SCREEN) {
            if (lp.width > HIGHER_METRICS || lp.height > HIGHER_METRICS) {
                if (lp.width > lp.height) {
                    lp.height = lp.height * HIGHER_METRICS / lp.width;
                    lp.width = HIGHER_METRICS;
                } else {
                    lp.width = lp.width * HIGHER_METRICS /lp.height ;
                    lp.height = HIGHER_METRICS;
                }

            }
        } else {
            if (lp.width > LOWER_METRICS || lp.height > LOWER_METRICS) {
                if (lp.width > lp.height) {
                    lp.height = lp.height * LOWER_METRICS / lp.width;
                    lp.width = LOWER_METRICS;
                 
                } else {
                    lp.width = lp.width * LOWER_METRICS /lp.height ;
                    lp.height = LOWER_METRICS;
                   
                }
            }
        }
    }
    
    
}
